%%%-------------------------------------------------------------------
%% @doc mqeg_misc public API
%% @end
%%%-------------------------------------------------------------------

-module(mqeg_misc).

% -include("debug.hrl").


%% --------------------------------------------------------------------
%% External exports
%% --------------------------------------------------------------------
-export([init_singleton/0]).
-export([set_singleton/2]).
-export([get_singleton/1]).

-export([spilt_query/1]).

-export([reply_index/1]).
-export([reply_404/1]).
-export([reply_200/2]).

-export([log_encode/1]).
-export([log_decode/1]).

%% ====================================================================
%% External functions
%% ====================================================================
init_singleton() ->
    ets:new(ets_singleton, [{keypos, 1}, named_table, public, set]),ok.

set_singleton(Name, Pid) ->
    ets:insert(ets_singleton, {Name, Pid}),ok.

get_singleton(Name) ->
    case ets:lookup(ets_singleton, Name) of
        [{_Name, Pid}] -> Pid;
        [] -> undefined
    end.


%% -------------------------------------------------------------------
spilt_query(<<>>) -> #{};
spilt_query(Body) ->
    Bodys = string:split(Body, "&", all),
    spilt_query(Bodys, #{}).

spilt_query([B | Bodys], Query) ->
    [K, V] = string:split(B, "="),
    spilt_query(Bodys, Query#{K => V});
spilt_query([], Query) ->
    Query.


%% -------------------------------------------------------------------
reply_index(Req0) ->
    cowboy_req:reply(302, #{<<"location">> => <<"/">>}, <<>>, Req0).

reply_404(Req0) ->
    cowboy_req:reply(404, #{}, <<>>, Req0).

reply_200(Req0, Data) ->
    cowboy_req:reply(200, #{<<"content-type">> => <<"application/json; charset=utf-8">>}, Data, Req0).


%% -------------------------------------------------------------------
log_encode(Term) ->
    erlang:list_to_binary( lists:flatten( io_lib:write( Term ) ) ).

log_decode(BinString) ->
    String = erlang:binary_to_list(BinString),
    {ok, T, _} = erl_scan:string(String++"."),
    {ok, Term} = erl_parse:parse_term(T),
    Term.

%% ====================================================================
%% Local functions
%% ====================================================================

